import 'package:flutter/material.dart';

import 'package:get/get.dart';

import '../../config/kq_global.dart';
import '../../resources/kq_images.dart';
import '../button/kq_ink_well.dart';
import '../image/kq_image.dart';

/// 图片容器
class KqImageBox extends StatefulWidget {
  /// 列数，默认4
  final int cols;

  /// 最大图片容量，默认8
  final int maxQty;

  /// 图片之间的间距，默认10
  final double? spacing;

  /// 图片类型和路径
  final List<ImageUrl> urls;

  /// 能否编辑，不能编辑则不显示删除和添加按钮，默认true
  final bool editable;

  /// 图片数量变化回调
  final Function()? onChanged;

  /// 图片添加按钮点击回调
  final Function(List<ImageUrl> urls, KqImageBoxState state)? onAddTap;

  /// 图片删除按钮点击回调
  final Function(List<ImageUrl> urls, ImageUrl imageUrl, int position,
      KqImageBoxState state)? onDeleteTap;

  /// 图片点击回调
  final Function(List<ImageUrl> urls, ImageUrl imageUrl, int position,
      KqImageBoxState state)? onImageTap;

  const KqImageBox(
      {Key? key,
      required this.urls,
      this.onAddTap,
      this.onDeleteTap,
      this.onImageTap,
      this.spacing,
      this.cols = 4,
      this.maxQty = 8,
      this.editable = true,
      this.onChanged})
      : super(key: key);

  @override
  KqImageBoxState createState() => KqImageBoxState();
}

class KqImageBoxState extends State<KqImageBox> {

  /// 刷新
  void update() {
    setState(() {});
    if (widget.onChanged != null) {
      widget.onChanged!();
    }
  }

  /// 图片数量
  int count() {
    return widget.urls.length;
  }

  /// 添加图片
  void addImage(ImageUrl imageUrl) {
    if (widget.maxQty != 0 && widget.urls.length >= widget.maxQty) {
      return;
    }
    widget.urls.add(imageUrl);
    update();
  }

  /// 拼接提交的url
  String? getSubmitUrls({join = ','}) {
    if (widget.urls.isEmpty) {
      return null;
    }
    var values = [];
    for (var url in widget.urls) {
      values.add(url.url);
    }
    return values.isEmpty ? null : values.join(join);
  }

  /// 拼接提交的valueForSubmit
  String? getSubmitValues({join = ','}) {
    if (widget.urls.isEmpty) {
      return null;
    }
    var values = [];
    for (var url in widget.urls) {
      if (url.valueForSubmit != null) {
        values.add(url.valueForSubmit);
      }
    }
    return values.isEmpty ? null : values.join(join);
  }

  /// 删除图片
  void remove(ImageUrl imageUrl) {
    widget.urls.remove(imageUrl);
    update();
  }

  List<Widget> _buildImages() {
    var imageCount = 0;
    List<Widget> list = [];
    imageCount = widget.urls.length;
    for (int i = 0; i < imageCount; i++) {
      ImageUrl imageUrl = widget.urls[i];
      list.add(_buildImageItem(imageUrl, i));
    }
    if (imageCount < widget.maxQty && widget.editable) {
      list.add(
        _buildImageItem(
            ImageUrl(
              imageType: ImageType.assets,
              url: KqImages.commonIcShangchuan,
              uploadOk: true,
              isAddBtn: true,
              package: KqGlobal.packageName,
            ),
            imageCount),
      );
    }
    return list;
  }

  /// 删除按钮
  Widget _buildDeleteButton() {
    return KqImage(
      imageType: ImageType.assets,
      url: KqImages.commonIcDelete,
      fit: BoxFit.fill,
      width: deleteBtnSize,
      height: deleteBtnSize,
      package: KqGlobal.packageName,
    );
  }

  /// 图片或新增按钮
  Widget _buildImageItem(ImageUrl imageUrl, int position) {
    return KqInkWell(
        onTap: () {
          if (imageUrl.isAddBtn) {
            if (widget.onAddTap != null) {
              widget.onAddTap!(widget.urls, this);
            }
          } else {
            if (widget.onImageTap != null) {
              widget.onImageTap!(widget.urls, imageUrl, position, this);
            }
          }
        },
        child: Stack(
          children: [
            KqImage(
              width: imageSize,
              height: imageSize,
              imageType: imageUrl.imageType,
              url: imageUrl.url,
              fit: BoxFit.cover,
              package: imageUrl.package,
            ),

            /// 删除按钮
            Visibility(
                visible: !imageUrl.isAddBtn && widget.editable,
                child: Positioned(
                    right: 0,
                    top: 0,
                    width: deleteBtnSize,
                    height: deleteBtnSize,
                    child: KqInkWell(
                      onTap: () {
                        if (widget.onDeleteTap != null) {
                          widget.onDeleteTap!(
                              widget.urls, imageUrl, position, this);
                        }
                      },
                      child: _buildDeleteButton(),
                    )))
          ],
        ));
  }

  double widgetWidth = 0;

  /// 每张图片大小DD
  double imageSize = 0;

  /// 删除按钮大小
  double deleteBtnSize = 0;

  @override
  Widget build(BuildContext context) {
    var spacing = widget.spacing ?? 10;
    widgetWidth = context.width;
    imageSize = (widgetWidth - spacing * (widget.cols - 1)) / widget.cols;
    deleteBtnSize = imageSize / 3;
    return GridView.count(
      crossAxisCount: widget.cols,
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      mainAxisSpacing: spacing,
      crossAxisSpacing: spacing,
      //宽高比
      childAspectRatio: 1 / 1,
      children: _buildImages(),
    );
  }
}

/// 图片类型和路径实体类
class ImageUrl {
  /// 图片类型
  ImageType imageType;

  /// 图片路径或链接
  String url;

  /// 是否上传完成，如果[url]是后端给的ossKey，则应该设置[uploadOk]为true。
  bool uploadOk;

  /// 用于提交给后端的数据，如果是oss的话，就是ossKey
  String? valueForSubmit;

  /// 自定义数据，用于存放临时数据
  dynamic extra;

  /// 包名，如果应用组件库内的图片，需要使用[KqGlobal.packageName]
  String? package;

  /// 是否新增按钮，组件内部使用，不用赋值
  bool isAddBtn;

  ImageUrl(
      {required this.imageType,
      required this.url,
      this.uploadOk = false,
      this.valueForSubmit,
      this.extra,
      this.package,
      this.isAddBtn = false});
}
